﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using BlueCMS.Core.Data;
using BlueCMS.Core.Data.Query;
using BlueCMS.Core.Entities;

namespace BlueCMS.Core.Services
{
    public class PageletService
    {
        public static IList<PageletInstance> GetPageletInstancesForRegionAndWebpage(string region, Webpage page)
        {
            IList<PageletInstance> instances;

            SelectQuery query = new SelectQuery();
            query.Select.All();
            query.From.Table("cms_pageletinstance_tbl");
            query.Where.Column("region_nm").Equals().Parameter(region).And().Column("webpage_id").Equals().Parameter(page.webpage_id);
            instances = query.ExecuteCollection<PageletInstance>();

            foreach (PageletInstance pi in instances)
            {
                query = new SelectQuery();
                query.Select.All();
                query.From.Table("cms_node_tbl");
                query.Where.Column("node_id").Equals().Parameter(pi.node_id);
                pi.Node = query.ExecuteObject<Node>();

                query = new SelectQuery();
                query.Select.All();
                query.From.Table("cms_pagelet_tbl");
                query.Where.Column("pagelet_id").Equals().Parameter(pi.pagelet_id);
                pi.Pagelet = query.ExecuteObject<Pagelet>();
            }

            return instances;
        }

        public static IList<PageletInstance> GetPageletInstancesForRegionAndTemplate(string region, Template template)
        {
            IList<PageletInstance> instances;

            SelectQuery query = new SelectQuery();
            query.Select.All();
            query.From.Table("cms_pageletinstance_tbl");
            query.Where.Column("region_nm").Equals().Parameter(region).And().Column("template_id").Equals().Parameter(template.template_id);
            instances = query.ExecuteCollection<PageletInstance>();

            foreach (PageletInstance pi in instances)
            {
                query = new SelectQuery();
                query.Select.All();
                query.From.Table("cms_node_tbl");
                query.Where.Column("node_id").Equals().Parameter(pi.node_id);
                pi.Node = query.ExecuteObject<Node>();

                query = new SelectQuery();
                query.Select.All();
                query.From.Table("cms_pagelet_tbl");
                query.Where.Column("pagelet_id").Equals().Parameter(pi.pagelet_id);
                pi.Pagelet = query.ExecuteObject<Pagelet>();
            }

            return instances;
        }
    }
}
